package com.tianruan.dc.modules.sys.user.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.tianruan.dc.common.utils.ApiVersionUtil;
import com.tianruan.dc.common.utils.SendSmsUtil;
import com.tianruan.dc.common.utils.response.VResponse;
import com.tianruan.dc.modules.sys.user.mapper.SmsCodeMapper;
import com.tianruan.dc.modules.sys.user.service.ISmsCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SmsCodeServiceImpl implements ISmsCodeService {

    @Autowired
    private SmsCodeMapper smsCodeMapper;

    /**
     * 发送短信验证码
     * @param phone
     */
    @Override
    public void sendSmsCode(String phone) {
        try {
            // 调用发送短信验证码的工具类
            String code = SendSmsUtil.sendSms(phone);
            // 插入短信日志记录到数据库中
            smsCodeMapper.insertSmsLog(phone, code);
        } catch (ClientException e) {
            e.printStackTrace();
            // 处理短信发送失败的情况
        }
    }

    /**
     * 验证短信验证码
     * @param phone
     * @param code
     * @return
     */
    @Override
    public boolean check(String phone, String code) {
        try {
            // 查询数据库中的验证码
            String smsCode = smsCodeMapper.selectSmsCode(phone);
            // 判断验证码是否一致
            if (smsCode.equals(code)) {
                return true;
            } else {
                return false;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 绑定手机号
     * @param id
     * @param phone
     */
    @Override
    public void bindphone(String id, String phone) {
        try {
            //绑定手机
            smsCodeMapper.updatePhoneNumberById(id, phone);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean checkId(String id) {
        try {
            if(smsCodeMapper.selectById(id)!=null){
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
